#!/usr/bin/python
#coding:utf-8

import serial
import struct
import binascii
import time
import getopt, sys, os
from intelhex import IntelHex

BPS = 57600;
START_ZERO = 0x00;
SEND_CMD = 0x01;
START_CHAR = 0x02;
ACK_OK = 0x06;
ACK_NOT = 0x15;


class BLE_Uart(object):
    buf = [];
    ser = 0;
    # fin = 0;

    def __init(self):
        pass

    def openport(self, name, bps):
        self.ser = serial.Serial(name, bps);

    def readfile(self, path):
        basename = os.path.basename(path);
        hexflag = True;
        try:
            basename.index(".hex");
            ih = IntelHex(path);
            ih.padding = 0x00;
            self.buf = ih.tobinstr();
        except ValueError:
            fin = open(path, "rb");
            self.buf = fin.read();
            fin.close();
        print "0x%02x" % len(self.buf);

    def waitstart(self):
        print "wait uart data, please reset power"
        data = struct.unpack("B", self.ser.read(1))[0];
        # print type(data);
        if data == START_ZERO:
            data = struct.unpack("B", self.ser.read(1))[0];
        if data == START_CHAR:
            print "0x%02x" % data;

    def sendbuflen(self):
        length = len(self.buf);
        d1 = length & 0xff;
        d2 = length >> 8;
        wr = struct.pack("BBB", SEND_CMD, d1, d2);
        self.ser.write(wr);
        ack = struct.unpack("B", self.ser.read(1))[0];
        if ack != ACK_OK:
            print "ACK_Error";
        else:
            print "ACK OK";

    def sendbuf(self):
        self.waitstart();
        self.sendbuflen();
        self.ser.write(self.buf);
        crc = struct.unpack("B", self.ser.read(1))[0];
        print "crc = 0x%02x" % crc;
        wr = struct.pack("B", ACK_OK);
        self.ser.write(wr);

    def sendconnect(self):
        self.sendbuf();

def main_func(com_port, filename):
    da14580 = BLE_Uart();
    da14580.readfile(filename);
    da14580.openport(com_port, BPS);
    da14580.sendconnect();

def usage():
    print("""Usage:
    -c --com_port portNumber    connect com port E.g /dev/ttyS0
    -f --file filename          Input file name
    -h --help                   Show this
    """);

if __name__ == '__main__':
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hc:f:", ["help", "com_port=", "file="])
    except getopt.GetoptError as err:
        print str(err)
        usage()
        sys.exit(2)
    com_port = None
    filename = None
    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("-c", "--com_port"):
            com_port = a
            print com_port
        elif o in ("-f", "--file"):
            filename = a
            print filename
        else:
            usage()
    if ((com_port == None) or (filename == None)):
        usage()

    main_func(com_port, filename)

